import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;


public class WifiControler extends Thread{

	static final int port = 8000;
	private Player player;
	private boolean state = true;

	public WifiControler(Player player) {
		this.player = player;
	}

	public void setPlayer(Player p){
		this.player = p;
	}

	public void kill(){
		state = false;
	}

	@Override
	public void run() {
		state = true;
		ServerSocket s = null;
		Socket soc = null;
		BufferedReader plec = null;
		PrintWriter pred = null;

		try{
			s = new ServerSocket(port);
			soc = s.accept();

			plec = new BufferedReader(new InputStreamReader(soc.getInputStream()));
			pred = new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())),true);

			while (state) {
				String str = plec.readLine(); 
				if(player != null ){
					try{
						String[] aux = str.split(":");
						Arrays.toString(aux);
						if(aux[0].equals("GAUCHE")) {
							player.goLeft();
							player.setCoefVitesse(Double.parseDouble(aux[1])*10);
						}
						else if(aux[0].equals("DROITE")) {
							player.goRight();
							player.setCoefVitesse(Double.parseDouble(aux[1])*10);
						}
						else
							player.stopMouvement();	
						
						if(aux.length > 2 && aux[2].equals("EGG"))
							player.dropAnEgg();
						else if(aux.length > 2 && aux[2].equals("SWITCH"))
							player.switchToNextBird();
						
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				pred.println("ALIVE");
				Thread.sleep(20);
			}

		} catch (Exception e) { System.out.println(e); }

		finally {
			try {
				s.close();
				soc.close();
				plec.close();
				pred.close();
			} catch (IOException e) { e.printStackTrace();}
		}
	}
}
